package cn.liontalk.service.impl;

import cn.liontalk.common.redis.RedisService;
import cn.liontalk.common.redis.prefix.MiaoShaKey;
import cn.liontalk.controller.LoginController;
import cn.liontalk.dao.GoodsDao;
import cn.liontalk.dao.OrderDao;
import cn.liontalk.dao.SecKillDao;
import cn.liontalk.entity.Goods;
import cn.liontalk.entity.MSOrder;
import cn.liontalk.entity.OrderInfo;
import cn.liontalk.entity.User;
import cn.liontalk.service.OrderService;
import cn.liontalk.service.SecKillService;
import cn.liontalk.util.MD5Util;
import cn.liontalk.util.UUIDutil;
import cn.liontalk.vo.GoodsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Random;

/**
 * @author: 周哲
 * @package: cn.liontalk.service.impl
 * @description:
 * @date: 2019/1/20 19:06
 * @version: V1.0
 */
@Service
public class SecKillServiceImpl implements SecKillService {

    private static Logger log = LoggerFactory.getLogger(LoginController.class);


    @Autowired
    private SecKillDao secKillDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private OrderDao orderDao;


    @Autowired
    private RedisService redisService;

    @Autowired
    private OrderService orderService;


    private void setKillGoodsOver(long goodsId) {
        redisService.set(MiaoShaKey.isGoodsOver, "" + goodsId, true);
    }

    private boolean getGoodsOver(long goodsId) {
        return redisService.keyExist(MiaoShaKey.isGoodsOver, "" + goodsId);
    }

    /**
     * 查询用户是否参与了重复秒杀
     *
     * @param goodId
     * @param uid
     * @return
     */
    @Override
    public OrderInfo queryGoodsKillInfoByGoodsIdAndUserId(long goodId, long uid) {
        return secKillDao.queryGoodsKillInfoByGoodsIdAndUserId(goodId, uid);
    }

    /**
     * 进行秒杀活动
     *
     * @param user    秒杀用户
     * @param goodsVO 商品信息
     * @return 秒杀的订单信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderInfo secKillGoods(User user, GoodsVO goodsVO) {
        Goods goods = new Goods();
        goods.setId(goodsVO.getId());
        goods.setGoodsStock(goodsVO.getGoodsStock() - 1);
        goodsDao.reduceSecKillGoodsStock(goods);
        int result = goodsDao.reduceGoodsStock(goods);
        if (result > 0) {
            return createOrderInfo(user, goodsVO);
        } else {
            return null;
        }
    }


    private OrderInfo createOrderInfo(User user, GoodsVO goodsVO) {

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(user.getId());
        orderInfo.setGoodsId(goodsVO.getId());
        orderInfo.setDeliveryAddressId(0L);
        orderInfo.setGoodsName(goodsVO.getGoodsName());
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsPrice(goodsVO.getGoodsPrice());
        orderInfo.setStatus(0);
        orderInfo.setCreateDate(new Date());
        orderInfo.setPayDate(null);
        orderDao.createOrderInfo(orderInfo);

        MSOrder msOrder = new MSOrder();
        msOrder.setGoodsId(goodsVO.getId());
        msOrder.setOrderId(orderInfo.getId());
        msOrder.setUserId(user.getId());
        secKillDao.createMsOrderInfo(msOrder);

        return orderInfo;
    }


    /**
     * 消息队列进行秒杀
     *
     * @param user    秒杀用户信息
     * @param goodsVO 秒杀商品信息
     */
    @Override
    public void mqSecKillGoods(User user, GoodsVO goodsVO) {
        Goods goods = new Goods();
        goods.setId(goodsVO.getId());
        goods.setGoodsStock(goodsVO.getGoodsStock() - 1);
        goodsDao.reduceSecKillGoodsStock(goods);
        int result = goodsDao.reduceGoodsStock(goods);
        boolean success = result > 0;
        if (success) {
            createOrderInfo(user, goodsVO);
        } else {
            setKillGoodsOver(goodsVO.getId());
        }
    }


    /**
     * 获取秒杀结果
     *
     * @param userid  用户ID
     * @param goodsId 商品ID
     * @return 返回结果
     */
    @Override
    public long getMiaoshaResult(long userid, long goodsId) {
        OrderInfo order = secKillDao.queryGoodsKillInfoByGoodsIdAndUserId(goodsId, userid);
        if (order != null) {
            return order.getId();
        } else {
            // 判断是排队中还是失败了
            boolean isOver = getGoodsOver(goodsId);
            if (isOver) {
                return -1;
            } else {
                return 0;
            }
        }
    }

    @Override
    public BufferedImage createVerifyCode(User user, long goodsId) {
        if (user == null || goodsId <= 0) {
            return null;
        }
        int width = 100;
        int height = 32;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        boolean result = redisService.set(MiaoShaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, rnd);
        log.info("SET VERIFY CODE IS " + result + ",CODE :" + redisService.get(MiaoShaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, int.class));
        //输出图片
        return image;
    }

    @Override
    public boolean checkVerifyCode(User user, long goodsId, Long verifyCode) {
        if (user == null || goodsId <= 0) {
            return false;
        }
        Integer codeOld = redisService.get(MiaoShaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, Integer.class);
        if (codeOld == null || codeOld - verifyCode != 0) {
            return false;
        }
        redisService.del(MiaoShaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId);
        return true;
    }

    @Override
    public String createMiaoshaPath(User user, long goodsId) {
        if (user == null || goodsId <= 0) {
            return null;
        }
        String str = MD5Util.md5(UUIDutil.getUUID() + "123456");
        redisService.set(MiaoShaKey.getMiaoshaPath, "" + user.getId() + "_" + goodsId, str);
        return str;
    }

    @Override
    public boolean checkPath(User user, long goodsId, String path) {
        if (user == null || goodsId <= 0) {
            return false;
        }
        String pathOld = redisService.get(MiaoShaKey.getMiaoshaPath, "" + user.getId() + "_" + goodsId, String.class);
        return path.equals(pathOld);
    }

    @Override
    public boolean checkCodeIsRight(User user, long goodsId, long verifyCode) {
        if (user == null || goodsId <= 0) {
            return false;
        }
        Integer codeOld = redisService.get(MiaoShaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, Integer.class);
        if (null == codeOld) {
            return false;
        }
        return verifyCode - codeOld == 0;
    }


    private static char[] ops = new char[]{'+', '-', '*'};

    /**
     * + - *
     */
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = "" + num1 + op1 + num2 + op2 + num3;
        return exp;
    }

    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer) engine.eval(exp);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}
